//
//  DDTagVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/13.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDTagVC.h"
#import "DDTagTextVC.h"
#import "DDTagDB.h"
#import "PECropViewController.H"
#import "DDNetWorkAPIClient.h"
@interface DDTagVC ()<UIPickerViewDataSource,UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,PECropViewControllerDelegate>
{
    //UIImage * paramImage_process;
    NSMutableArray * array_picker;
}
@property (weak, nonatomic) IBOutlet UIView *v1;
@property (weak, nonatomic) IBOutlet UIView *v2;
@property (weak, nonatomic) IBOutlet UIView *v3;
@end

@implementation DDTagVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.voice = [[LCVoice alloc] init];
    _v1.layer.cornerRadius = 10.0;
    _v2.layer.cornerRadius = 10.0;
    _v3.layer.cornerRadius = 10.0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)recordEnd:(id)sender {
     self.view.hidden = YES;
    [self.voice stopRecordWithCompletionBlock:^{
        
        if (self.voice.recordTime > 0.0f) {
            //            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"\nrecord finish ! \npath:%@ \nduration:%f",self.voice.recordPath,self.voice.recordTime] delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            //            [alert show];
            
            
            _type = @"AUDIO";
            __weak DDTagVC *weakSelf = self;
            DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
            NSData *data = [NSData dataWithContentsOfFile:self.voice.recordPath];
            NSString *dataString = [data base64Encoding];
            [network uploadFile:@{@"extName":@"caf",@"data":dataString} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                
                if (object) {
                    NSDictionary *dict = (NSDictionary *)object;
                    
                    
                    
                    DDTagDB *tagDB = [[DDTagDB alloc] init];
                    tagDB.x = weakSelf.x;
                    tagDB.y = weakSelf.y;
                    tagDB.tagIndex = weakSelf.index;
                    tagDB.type = weakSelf.type;
                    tagDB.result = [dict objectForKey:@"data"];//self.voice.recordPath;
                    tagDB.qid = weakSelf.qid;
                    if (![tagDB saveToDB]) {
                        NSLog(@"插入TagDB数据库失败");
                    }
                    
                    if (_result) {
                        _result(weakSelf.voice.recordPath,nil,weakSelf.type);
                    }
                    [weakSelf dismissViewControllerAnimated:YES completion:nil];
                    
                    
                }else{
                    NSLog(@"上传失败");
                }
                
            }];
            
        }
    }];
}
- (IBAction)recordCancel:(id)sender {
    [self.voice cancelled];
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"取消了" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
    [alert show];
}
- (IBAction)recordStart:(id)sender {
    
    [self.voice startRecordWithPath:[NSString stringWithFormat:@"%@/Documents/MySound_%f.caf", NSHomeDirectory(),[[NSDate date] timeIntervalSince1970]]];
}


- (IBAction)imageAction:(id)sender {
   // _type = @"IMAGE";
     self.view.hidden = YES;
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"打开相册",@"立即拍照", nil];
    
     [sheet showInView:self.view];

}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self openPhoto];
    }else if (buttonIndex == 1) {
        [self openCamera];

    }
}
- (void)openCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }
}
- (void)openPhoto {
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
}


- (IBAction)textAction:(id)sender {
    self.view.hidden = YES;
    _type = @"TEXT";
    DDTagTextVC *textVC = [[DDTagTextVC alloc] initWithNibName:@"DDTagTextVC" bundle:nil];
    [self presentViewController:textVC animated:YES completion:^{
        textVC.reslutText = ^(NSString *result)
        {
            DDTagDB *tagDB = [[DDTagDB alloc] init];
            tagDB.x = _x;
            tagDB.y = _y;
            tagDB.tagIndex = _index;
            tagDB.type = _type;
            tagDB.result = result;
            tagDB.qid = _qid;
            if (![tagDB saveToDB]) {
                NSLog(@"插入TagDB数据库失败");
            }
    
            if (_result) {
                _result(result,nil,_type);
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        };
    }];
}

- (IBAction)openEditor:(id)sender
{
    PECropViewController *controller = [[PECropViewController alloc] init];
    controller.delegate = self;
    controller.image = _paramImage_process;
    
    UIImage *image = _paramImage_process;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    CGFloat length = MIN(width, height);
    controller.imageCropRect = CGRectMake((width - length) / 2,
                                          (height - length) / 2,
                                          length,
                                          length);
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    
    [self presentViewController:navigationController animated:YES completion:nil];
}

#pragma mark - picker dataSource & delegate
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return array_picker.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return array_picker[row];
}

#pragma mark - pickerImage Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    _paramImage_process = image;
    [picker dismissViewControllerAnimated:YES completion:^{
        [self openEditor:nil];
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -  PECropViewControllerDelegate
- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage{
    [controller dismissViewControllerAnimated:YES completion:nil];
    _paramImage_process = croppedImage;
    
    
    _type = @"IMAGE";
    
   
    
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
    NSData *data = UIImageJPEGRepresentation(_paramImage_process, 0.1);
    NSString *dataString = [data base64Encoding];
    [network uploadImage:@{@"extName":@"jpg",@"data":dataString} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        
        if (object) {
            NSDictionary *dict = (NSDictionary *)object;
            DDTagDB *tagDB = [[DDTagDB alloc] init];
            tagDB.x = _x;
            tagDB.y = _y;
            tagDB.tagIndex = _index;
            tagDB.type = _type;
            tagDB.result = [dict objectForKey:@"data"];
            tagDB.qid = _qid;
            if (![tagDB saveToDB]) {
                NSLog(@"插入TagDB数据库失败");
            }
            
            if (_result) {
                _result(self.voice.recordPath,_paramImage_process,_type);
            }
           
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            NSLog(@"上传失败");
        }
        
    }];
    
}

- (void)cropViewControllerDidCancel:(PECropViewController *)controller{
    [controller dismissViewControllerAnimated:YES completion:nil];
}



@end
